import axios from 'axios'
import Cookies from 'js-cookie'
import WConfig from "@/config";
import { InputChangeEvent } from '@/utils/type/global'
import store from '@/store'
import { Notification } from 'element-ui'

// 创建axios实例
const service = axios.create({
  timeout: 30000, // 请求超时时间
  baseURL: process.env.VUE_APP_NGINX_HEADER
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    WConfig.print('================= url ==================')
    WConfig.print(config.url)
    WConfig.print('================= 参数 ==================')
    WConfig.print(config.method === 'get' ? config.params : config.data)
    // 所有请求都带上项目名称
    config.headers.PROJECT = WConfig.projectConfig.projectKEY
    // 设置 token
    if (store.getters.token) {
      config.headers.token = store.getters.token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  },
)

// respone拦截器
service.interceptors.response.use(
  (response) => {
    const { status, data: resData } = response
    const { code, data, msg } = resData
    if (response.headers.token) {
      store.commit('SET_TOKEN', response.headers.token)
    }
    WConfig.print('================= response ==================', response.config.url)
    WConfig.print(resData, status)
    if (code !== 0) {
      if (code === 401) {
        store.dispatch('FED_LOG_OUT')
        WConfig.router.replace('/login')
      }
      Notification.error(msg || '网络错误')
      return Promise.reject(resData)
    } else {
      return data
    }
  },
  (error) => {
    const { message } = error
    Notification.error(message)
    return Promise.reject(error)
  },
)

// 自定义封装git
export function get<T>(url: string, params = {}): Promise<T> {
  return service.get(url, {
    // 请求参数
    params,
  })
}

// 自定义封装git
export function del<T>(url: string, params = {}): Promise<T> {
  return service.delete(url, {
    headers: {
      'x-csrf-token': Cookies.get('csrfToken')
    },
    // 请求参数
    params,
  })
}

// 自定义封装POST
export function post<T>(url: string, params = {}): Promise<T> {
  return service.post(url, params, {
    headers: {
      'x-csrf-token': Cookies.get('csrfToken')
    }
  })
}

// 图片上传
export function upImage(url: string, name: string, e: InputChangeEvent) {
  const { files } = e.target
  const [file] = files || []
  // 判断图片大小，超出后直接返回
  const fileSize = file.size || 0
  if (fileSize > (2 * 1024 * 1024)) {
    return Promise.reject({
      code: 1,
      msg: '图片大小不能超所2M',
    })
  }
  // 创建form对象
  const params = new FormData()
  // 通过append向form对象添加数据
  params.append(name, file, file.name)
  return service.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'x-csrf-token': Cookies.get('csrfToken')
    },
  })
}

// 上传文件
export function upFile(url: string, params = {}) {
  return service.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'x-csrf-token': Cookies.get('csrfToken')
    },
  })
}
